var adding_driver_boolean = false;
var driver_list = [];

var setRowColors = function () {
    $("#driverLog tbody").removeClass('tableAlternateColor');
    $("#driverLog tbody:odd").addClass('tableAlternateColor');
};

function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json){
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name+'</a> '+
                      'Phone: (' + json.tmpo_poc_phone.substr(0,3) + ') ' +
                      json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    ); 
}

function toggleButtons(x) {
	if (!x){
		$("#addDriver").unbind();
	    $("#button_print").unbind();
		$("#addDriver").addClass('buttonInactive');
	    $("#button_print").addClass('buttonInactive');
	}else{
		$("#button_print").click(makePrinter("#driverLog"));
    	$("#addDriver").click(function () {
        		if (adding_driver_boolean){
		            $("#message").remove();
		            $("#cancel_00").after(
		            '<span class="generalErrorMessage" '+
		            'name="message" id="message"><img alt="" '+
		            'src="/tmpo/images/icons/alert.gif"/>'+
		            'Only one driver may be added at a time.</span>');		        
        		}else{
					toggleButtons(false);
	    	        adding_driver_boolean = true;
    	    	    addDriver();
		            $("#add_new_driver").click(function () {
		                if( validateRequestForm("cancel_00") ) { 
							toggleButtons(true);
		                    addRequest();
        		        }
		            });
		        }
		        return false;
    	});
		$("#addDriver").removeClass('buttonInactive');
		$("#button_print").removeClass('buttonInactive');
	}
}

var addRequest = function () {
    var form_data_insert = {
        name: $("#name").val(),
        position: $("#position").val(),
        telephone: $("#phone_area").val()+'-'+$("#phone_prefix").val()+'-'+
            $("#phone_suffix").val(),
        address: $("#address").val(),
        license_number: $("#license_number").val(),
        license_expiration: $.d2m3y4_to_y4m2d2($("#license_expiration").val()),
        license_class: $("#license_class").val(),
        license_endorsements: $("#license_endorsements").val(),
        license_restrictions: $("#license_restrictions").val()
    };
    $.ajax({
        url: '/api/tmpo/drivers/',
        type: 'PUT',
        data: form_data_insert,
        success: function() { console.debug("success"); },
        complete: function() {
            resetTable();
        },
        error: function(xhr, err, exc) {
            if (xhr.status == 409) {
                $("#name").parent().append("<br>Duplicate driver name.");
                $("#name").parent().addClass("tableErrorColor");
                $("#name").addClass("formError");
            }
            gdata = [xhr, err, exc];
        }
    });
};

var editRequest = function(id) {    
    var form_data_update = {
        name: $("#name").val(),
        position: $("#position").val(),
        telephone: $("#phone_area").val()+'-'+$("#phone_prefix").val()+'-'+
            $("#phone_suffix").val(),
        address: $("#address").val(),
        license_number: $("#license_number").val(),
        license_expiration: $.d2m3y4_to_y4m2d2($("#license_expiration").val())+
            ' 01:00',
        license_class: $("#license_class").val(),
        license_endorsements: $("#license_endorsements").val(),
        license_restrictions: $("#license_restrictions").val()
    };
    $.ajax({
        url: '/api/tmpo/drivers/' + id + '/',
        type: 'POST',
        data: form_data_update,
        success: function(){ console.debug("Success"); },
        complete: function() { resetTable(); },
        error: function(){ console.debug("fail"); }
    });
};

var validateRequestForm = function (last_btn){
    var date_error_message = "Please enter a complete "+
                             "date.<br>Example: 01 JAN 2000";
    var error_count = 0;
    $("#message").remove();
    $("td[class='tableErrorColor']").removeClass("tableErrorColor");
    $("span[class='errorMessage']").remove();
    $("input[class='formError']").removeClass('formError');
    $("td br").remove();
    if( !$.is_d2m3y4($("#license_expiration").val())) {
        error_count++;
        $("#license_expiration").parent().append(
            '<br/><span class="errorMessage">'+date_error_message+'</span>');
        $("#license_expiration").parent().addClass("tableErrorColor");
        $("#license_expiration").addClass("formError");
    }
    var message_error_required = '<br><span class="errorMessage">' +
                'Please complete required field.</span>';
    var required_fields = ['name','address','license_number','license_class',
                           'license_endorsements','license_restrictions'];                           
    jQuery.map(required_fields, function(field) { 
        if( !$("#"+field).val()) {
            error_count++;
            $("#"+field).parent().append(message_error_required);
            $("#"+field).parent().addClass("tableErrorColor");
            $("#"+field).addClass("formError");
        }
    });  
    var phone_error_message = '<br><span class="errorMessage">' +
                    'Please enter a 10-digit telephone number. ' +
                    'Example: 123-456-7890</span>';                              
    var required_phone_fields = ['phone_area', 'phone_prefix'];    
    var required_phone_suffix = ['phone_suffix'];    
    if (validPhoneThree($("#phone_area").val()) && 
        validPhoneThree($("#phone_prefix").val()) && 
        validPhoneFour($("#phone_suffix").val())) {
    } else {
        error_count++;
        $("#phone_suffix").parent().append(phone_error_message);
        $("#phone_suffix").parent().addClass("tableErrorColor");
        $("#phone_area, #phone_prefix, #phone_suffix").addClass("formError");
    }
    if(error_count){
        $("#"+last_btn).after(
        '<span class="generalErrorMessage" name="message" id="message">'+
        '<img alt="" src="/tmpo/images/icons/alert.gif"/>'+
        'Please correct errors above to save form.</span>');
    }else {
        $("#message").remove();
        $("#"+last_btn).after(
            '<span id="message" name="message" class="waitMessage">'+
            '<img src="/tmpo/images/icons/hourglass.gif" alt="" />'+
            'Your changes are being saved. Please wait.</span>');
        return true;
    }
};

var cancelAddDriver = function() {
    $("#tbody_add").remove();
    adding_driver_boolean = false;    
};

var cancelEditDriver = function() {
    $("#tbody_edit").remove();
    adding_driver_boolean = false;
};

var bindRows = function () {
    jQuery.map(driver_list, function(row) {
        if( $("#tbody_" + row.id+":has[class!='highlight']").length ){
            $("#tbody_" + row.id).unbind();
            $("#tbody_" + row.id).hover(function () { 
                $("#tbody_" + row.id).addClass('highlight');
            },function () {
                $("#tbody_" + row.id).removeClass('highlight');
            });
            $("#span_detail_" + row.id).click(function () {
                location.href = "/tmpo/drivers/detail/?id=" + row.id;
            });
            $("#tbody_" + row.id + " tr td").click(function () { 
                editDriver(row);
                return false; 
            });
            $("#span_edit_" + row.id).click(function () { 
                editDriver(row);
                return false;
            });  
            $("#tbody_" + row.id + " tr td span").parent().unbind();
        }
    });
};

var getDrivers = function() {
    $.getJSON(
        '/api/tmpo/drivers/',
        function(json) {
            driver_list = [];
            driver_list = $(json.drivers);
            jQuery.map(json.drivers, function(n) {
                $("#driverLog").append(
                "<tbody class='tableAlternateColor' id='tbody_"+
                n.id+"'><tr><td><span id='span_edit_"+
                n.id+"'class='hoverButton'>"+
                "Edit</span><span id='span_detail_"+
                n.id+"'class='hoverButton'"+
                " style='margin-top:15px;'>Detail</span>"+
                n.name+"</td><td>"+ 
                n.telephone+"</td><td>"+n.address+"</td><td>"+
                n.license_number+"</td><td>"+$.y4m2d2_to_d2m3y4(
                n.license_expiration.replace(/:|-| /g, " ").substr(0,10))+
                "</td><td>"+n.license_class+"</td><td>"+
                n.license_endorsements+
                "</td><td>"+n.license_restrictions+
                "</td></tr></tbody>");
            });
            setRowColors();
            bindRows();
        }
    );
};

var resetTable = function() {
    $("#driverLog tbody").remove();
    getDrivers();
    cancelAddDriver();
    cancelEditDriver();
	toggleButtons(true);
};

var addDriver = function() {
    $("#driverLog tbody").unbind();    
	  toggleButtons(false);	
    $("#driverLog").prepend(
        "<tbody class='tableActiveColor' id='tbody_add'><tr>"+
        "<td><input name='name' type='text' size='12' id='name' /></td>"+
        "<td><input id='phone_area' type='text' maxlength='3' size='3' "+
        "name='phone_area' value='907'/>-<input id='phone_prefix' type='text'"+
        " maxlength='3'size='3'name='phone_prefix'/>-<input id='phone_suffix'"+
        " type='text' maxlength='4' size='4' name='phone_suffix'/></td>" + 
        "<td><input name='address' type='text' size='12' id='address' /></td>"+
        "<td><input name='license_number' type='text' size='9' "+
        "id='license_number' /></td><td><input name='license_expiration' "+
        "type='text' size='9' id='license_expiration'  />" +
        "<h6 id='exp_date'>DD MMM YYYY</h6></td><td><input "+
        "name='license_class' type='text' size='2' id='license_class' />"+
        "</td><td><input name='license_endorsements' type='text' size='9'"+
        " id='license_endorsements' /></td><td>"+
        "<input name='license_restrictions' type='text' size='9' "+
        "id='license_restrictions' /></td></tr><tr><td colspan='9'>"+
        "<a class='button' href='#'id='add_new_driver' >" +
        "<img src='/tmpo/images/icons/save.gif' alt='' />Save</a>" +
        "<a class='button' href='#'id='cancel_00'>"+
        "<img src='/tmpo/images/icons/close.gif' alt='' />" +
        "Cancel</a></td></tr></tbody>");        
        $("#cancel_00").click(function() { 
            toggleButtons(true);
            cancelAddDriver();
            bindRows();
            return false;
        });
};

function deleteRequest(row) {
    var deleteCommitment = function(){
        $.ajax({
            type: "DELETE",
            url: '/api/tmpo/drivers/'+row.id+'/',
            dataType: "text",
            success: function() { console.debug("success");},
            complete: function() { console.debug("complete"); },
            error: function() { console.debug("fail");}
        });
        clearTimeout(timeout_index);
        delete timeout_index;
    };
    timeout_index = setTimeout(deleteCommitment, 10000);
    $(window).unload( function (){
        if( typeof(timeout_index) != 'undefined' ){ 
            deleteCommitment();
        }
    });
    $("#tbody_edit tr").remove();
    $("#tbody_edit").append('<tr><td colspan="10"><b>'+
        'This driver has been deleted. <span id="close_delete_'+row.id+'"'+
        ' class="inferLink"><u>Close</u></span> | <span id="undo_delete_'+ 
        row.id+'" class="inferLink"><u>Undo</u></span></b></td></tr>');
    bindRows();
    $("#close_delete_" + row.id).click(function () {
        deleteCommitment(); 
        resetTable();
        return false;
    });
    $("#undo_delete_" + row.id).click(function () {
        clearTimeout(timeout_index); 
        delete timeout_index;
        resetTable();
        return false; 
    });
}

var editDriver = function (row) {
    $("#driverLog tbody").unbind();
	toggleButtons(false);
    $("#tbody_" + row.id).replaceWith(
        "<tbody class='highlight' id='tbody_edit'><tr>" +
        "<td><span id='span_edit_"+row.id+"' class='hoverButton'>Edit</span>"+
        "<span id='span_detail_" + row.id + "' class='hoverButton' "+
        "style='margin-top:15px;'>Detail</span><input name='name' type='text'"+
        " size='12' id='name' value='" +row.name+"' /></td><td>"+
        "<input id='phone_area' type='text' maxlength='3' size='3' "+
        "name='phone_area' value='"+row.telephone.substr(0,3)+"' />-" +
        "<input id='phone_prefix' type='text' maxlength='3' size='3' "+
        "name='phone_prefix' value='"+row.telephone.substr(4,3)+"'/>-" +
        "<input id='phone_suffix' type='text' maxlength='4' size='4' "+
        "name='phone_suffix' value='"+row.telephone.substr(8,4)+"'/></td>" +
        "<td><input name='address' type='text' size='12' id='address' value='"+
        row.address+"' /></td><td><input name='license_number' type='text' "+
        "size='9' id='license_number' value='"+row.license_number+"' /></td>"+
        "<td><input name='license_expiration' type='text' size='9' "+
        "id='license_expiration' value='"+
        $.y4m2d2_to_d2m3y4(row.license_expiration.replace(
        /:|-| /g, " ").substr(0,10))+"'/>"+
        "<h6 id='exp_date'>DD MMM YYYY</h6></td><td>"+
        "<input name='license_class'type='text' size='2' id='license_class' "+
        "value='"+row.license_class+"' /></td><td>"+
        "<input name='license_endorsements' type='text' size='9' "+
        "id='license_endorsements' value='"+row.license_endorsements+"' />"+
        "</td><td><input name='license_restrictions' type='text' size='9' "+
        "id='license_restrictions' value='"+row.license_restrictions+"' />"+
        "</td></tr><tr><td colspan='9'><a class='button' "+
        "href='#'id='edit_driver' ><img src='/tmpo/images/icons/save.gif' "+
        "alt='' />Save</a><a class='button' href='#'id='cancel_00'>"+
        "<img src='/tmpo/images/icons/close.gif' alt='' />Cancel</a>"+
        "<a class='button' href='#'id='delete_00'>"+
        "<img src='/tmpo/images/icons/delete.gif' alt='' />Delete</a>"+
        "</td></tr></tbody>");        
        $("#span_edit_" + row.id).addClass('inactive');
        $("#span_detail_" + row.id).click(function () { 
            location.href = "/tmpo/drivers/detail/?id=" + row.id; 
        });
    $("#cancel_00").click(function() {
        resetTable();
        return false;
    });    
    $("#edit_driver").click(function (){
        if( validateRequestForm("delete_00")) {  
            toggleButtons(true);
			editRequest(row.id);
        }
        return false;
    });    
    $("#delete_00").click(function () {
		toggleButtons(true);
		deleteRequest(row);
		return false;
	});
};

$(function() {
    Functional.install();
    getSiteCfg();
    getDrivers();
    $("#button_print").click(makePrinter("#driverLog"));
    $("#addDriver").click(function () {
        if (adding_driver_boolean){
            $("#message").remove();
            $("#cancel_00").after('<span class="generalErrorMessage" '+
            'name="message" id="message"><img alt="" '+
            'src="/tmpo/images/icons/alert.gif"/>Only one driver may '+
            'be added at a time.</span>');
        }else {
            toggleButtons(false);
            adding_driver_boolean = true;
            addDriver();
            $("#add_new_driver").click(function () {
                if( validateRequestForm("cancel_00") ) {
                    toggleButtons(true);
                    addRequest();
                }
            });
        }
        return false;
    });
});
